<template>
  <a-modal
    :visible="visible"
    title="新增"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      ref="formRef"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
      :model="formData"
      :rules="formRules"
    >
      <a-form-item label="时间" name="time" v-if="ifPlan || ifReport">
        <a-date-picker
          @change="onDateChange"
          v-model:value="formData.time"
          style="width: 80%"
        ></a-date-picker>
      </a-form-item>
      <a-form-item label="时间" name="ybTime" v-if="ifDay">
        <a-month-picker
          @change="onDateChange"
          v-model:value="formData.ybTime"
          style="width: 80%"
        ></a-month-picker>
      </a-form-item>
      <a-form-item label="监理规划" name="fileList" v-if="ifPlan">
        <a-upload
          :file-list="fileList"
          :remove="handleRemove"
          :before-upload="beforeUpload"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            点击上传
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="监理月报" name="fileList" v-if="ifDay">
        <a-upload
          :file-list="fileList"
          :remove="handleRemove"
          :before-upload="beforeUpload"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            点击上传
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="专项报告" name="fileList" v-if="ifReport">
        <a-upload
          :file-list="fileList"
          :remove="handleRemove"
          :before-upload="beforeUpload"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            点击上传
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="formData.remark"></a-textarea>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { message } from "ant-design-vue";
import { defineProps, defineEmits, ref, watch } from "vue";
import {
  postjlgzUpload,
  postjlgzSaveOrUpdate,
} from "@/api/module/constructAndImplement";
import global from "../../../global/global.vue";

const props = defineProps({
  visible: Boolean,
  activeKey: String,
  editData: Object,
});
const emits = defineEmits(["close"]);

// 项目id
const projectId = global.xmid;

const labelCol = { span: 7 };
const wrapperCol = { span: 17 };

// 表单实例
const formRef = ref();

// 表单校验
const specialValidator = (rule, value, callback) => {
  if (fileList.value.length === 0) {
    callback(new Error("请上传文件"));
  } else {
    callback();
  }
};
const formRules = {
  time: [{ required: true, message: "请选择", trigger: "change" }],
  ybTime: [{ required: true, message: "请选择", trigger: "change" }],
  fileList: [{ validator: specialValidator, trigger: "blur" }],
  remark: [{ required: true, message: "请选择", trigger: "blur" }],
};

// 表单数据
const formData = ref({
  remark: "",
  ybTime: "",
  time: "",
});

// 监听数据的变化
watch(
  () => props.editData,
  (newV, oldV) => {
    formData.value = Object.assign({}, newV);
    if (newV.file) {
      fileList.value = [
        {
          name: newV.fileName,
          id: newV.file,
        },
      ];
      id.value = newV.file;
    }
  }
);

// 监听activeKey变化
const ifPlan = ref(true);
const ifDay = ref(false);
const ifReport = ref(false);
watch(
  () => props.activeKey,
  (newV, oldV) => {
    if (newV === "0") {
      ifPlan.value = true;
      ifDay.value = false;
      ifReport.value = false;
    } else if (newV === "1") {
      ifPlan.value = false;
      ifDay.value = true;
      ifReport.value = false;
    } else if (newV === "2") {
      ifPlan.value = false;
      ifDay.value = false;
      ifReport.value = true;
    }
  }
);

// 选择日期
const onDateChange = (date, dateString) => {
  formData.value.ybTime = dateString;
};

// 文件上传
const fileList = ref([]);

// 判断文件类型
const allowedTypes = [
  "application/pdf",
  "application/msword",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "application/vnd.ms-excel",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
];

// 上传列表的删除
const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  id.value = "";
};

// 上传之前操作
const beforeUpload = (file) => {
  const isType = allowedTypes.includes(file.type);
  if (!isType) {
    return message.error("请选择正确的文件类型!");
  }
  fileList.value = [file];
  id.value = "";
  return false;
};

// 清除数据和校验
const clearFormData = () => {
  fileList.value = [];
  formRef.value.resetFields();
};

/* 提交取消 */
const id = ref("");
const submit = async () => {
  await formRef.value.validate();
  // 上传文件
  if (!id.value) {
    const formDataData = new FormData();
    formDataData.append("file", fileList.value[0]);
    formDataData.append("type", props.activeKey);
    const res = await postjlgzUpload(formDataData);
    id.value = res.data.id;
  }
  // 提交接口
  if (props.activeKey === "0" || props.activeKey === "2") {
    if (formData.value.id) {
      await postjlgzSaveOrUpdate({
        file: id.value,
        id: formData.value.id,
        remark: formData.value.remark,
        type: props.activeKey,
        xmid: projectId,
        time: formData.value.time,
      });
    } else {
      await postjlgzSaveOrUpdate({
        file: id.value,
        remark: formData.value.remark,
        type: props.activeKey,
        xmid: projectId,
        time: formData.value.time,
      });
    }
  } else if (props.activeKey === "1") {
    const result = await postjlgzSaveOrUpdate({
      file: id.value,
      remark: formData.value.remark,
      type: props.activeKey,
      xmid: projectId,
      ybTime: formData.value.ybTime,
    });
    if (result.data.code === 300) {
      message.warn(result.data.msg);
    }
  }
  clearFormData();
  emits("close", false);
};

const cancel = () => {
  clearFormData();
  emits("close", false);
};

const tokenKey = localStorage.getItem("token_key");
const token = localStorage.getItem("token");
const headers = {
  Authorization: token,
  "Authorization-key": tokenKey,
};
</script>
